import { sendMobileCodeAPI } from "@/services/user";
import type { CodeType } from "@/types/user";
import { showNotify, type FormInstance } from "vant";
import { onUnmounted, ref, type Ref } from "vue";


//倒计时
const time = ref(0)
let timeId:number
const form = ref<FormInstance>()
export function useMobileCode(mobile:Ref<string>,type:CodeType='login'){
     //发送验证码
 const send = async() => {
    // 已经倒计时time的值大于0，此时不能发送验证码
    if(time.value > 0) return
    await form.value?.validate('mobile')
    const res = await sendMobileCodeAPI(mobile.value,type)
    console.log('验证码',res.data.code);
    showNotify({
      message:res.data.code,
      duration:6000,
      color:'black',
      background:'skyblue'
    })
    //倒计时
    clearInterval(timeId)
    timeId = window.setInterval(()=>{
      time.value--
      if(time.value <=0){clearInterval(timeId)}
    },1000)
   }
   onUnmounted(()=>{
    // 组件销毁时，清除定时器
    window.clearInterval(timeId)
  })
  return{send,time,form}
}